import wepy from 'wepy';

export default class Home extends wepy.mixin {
  data = {
    // 保存传递过来的商品id
    goods_id: 0,
    // 保存商品信息
    goods_info: [],
    // 保存地址信息
    address: wepy.getStorageSync('assress') || null,
  };

  methods = {
    // 点击轮播图图片预览大图
    previewImage(current) {
      // 参数 urls 预览图片数组  current 点击的图片
      const urls = this.goods_info.pics.map((item) => item.pics_big);
      wepy.previewImage({ urls, current });
    },
    // 点击选择收货地址 调用微信地址api
    async chooseAddress() {
      const res = await wepy.chooseAddress().catch((err) => err);
      console.log(res);
      if (res.errMsg !== 'chooseAddress:ok')
        return wepy.baseToast('添加地址失败');
      wepy.baseToast('保存地址成功');
      this.address = res;
      wepy.setStorageSync('assress', res);
    },
    // 点击加入购物车
    addgoodstocart() {
      // const goods = {
      //   id: this.goods_info.goods_id,
      //   price: this.goods_info.goods_price,
      //   name: this.goods_info.goods_name,
      //   count:1
      // };
      const { goods_id, goods_price, goods_name ,goods_big_logo} = this.goods_info;
      // this.$parent 从app.wpy 拿到数据
      this.$parent.addGoodsTo(goods_id, goods_price, goods_name ,goods_big_logo)
    },
  };

  computed = {
    // 使用计算属性 es6 结构数据 获取收货地址
    addresStr() {
      if (this.address === null) return '请选择收货地址';
      const {
        provinceName,
        cityName,
        countyName,
        detailInfo,
        userName,
      } = this.address;
      return provinceName + cityName + countyName + detailInfo + userName;
    },
    // 获取购物车里的商品数量
    goodNum(){
      return this.$parent.globalData.cate.length
    }
  };

  async getGoodsInfo() {
    const { data: res } = await wepy.get('/goods/detail', {
      goods_id: this.goods_id,
    });
    if (res.meta.status !== 200) return wepy.baseToast();
    this.goods_info = res.message;
    this.$apply();
  }

  onLoad(options) {
    this.goods_id = options.goods_id;
    this.getGoodsInfo();
  }
}
